package com.ptkc.data.repository;

import com.ptkc.constants.Page;
import com.ptkc.constants.WebResult;
import com.ptkc.err.RunfastException;
import org.apache.http.Header;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.rest.RestStatus;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author: Mr.Jiao
 * @date: 2018年11月17日
 */
@Component
public class IElasticsearchRepository implements ElasticsearchRepository {


    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Override
    public Page search(SearchRequest request, Pageable pageable, Header... headers) throws IOException {
        System.out.println(request.source().toString());
        SearchResponse response = restHighLevelClient.search(request);
        RestStatus restStatus = response.status();
        if(restStatus != RestStatus.OK){
            RunfastException.throwErr("搜索引擎连接失败");
        }else{
            SearchHits hits = response.getHits();
            SearchHit[] hit_array = hits.getHits();
            List<Object> objs = new ArrayList<>();
            if (hit_array != null && hit_array.length > 0) {
                for (SearchHit hit : hit_array) {
                    objs.add(hit.getSourceAsMap());
                }
            }
            return new Page<Object>((int)hits.getTotalHits(), pageable.getPageNumber(), pageable.getPageSize(), objs);
        }
        return null;
    }

}
